package com.justnow.offer;

/**
 * @author justnow
 * Created on 2020-09-15
 * Description
 */
public class Solution48 {
    public static void main(String[] args) {
        Solution48 solution48 = new Solution48();

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        ListNode listNode = solution48.swapPairs2(node1);
        System.out.println(listNode);
    }

    public ListNode swapPairs(ListNode head) {
        ListNode dummpy = new ListNode(-1);
        dummpy.next = head;
        ListNode prevNode = dummpy;
        while (head != null || head.next != null) {
            ListNode first = head;
            ListNode second = head.next;

            prevNode.next = second;
            first.next = second.next;
            second.next = first;

            prevNode = first;
            head = first.next;// jump
        }
        return dummpy.next;
    }


    /**
     * 方法二，递归解法
     * @param head
     * @return
     */
    public ListNode swapPairs2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode second = head.next;
        head.next = swapPairs2(second.next);
        second.next = head;
        return second;
    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        this.val = x;
    }
}



